package com.erp.app.common.insert.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.erp.app.common.ProjectConstants;
import com.erp.framework.exceptions.CreateRecordException;
import com.erp.framework.exceptions.DeleteRecordException;
import com.erp.framework.exceptions.FindRecordException;
import com.erp.framework.exceptions.ModifyRecordException;
import com.erp.framework.model.dao.SimpleBaseDao;
import com.erp.framework.model.vo.ChildList;
import com.erp.framework.model.vo.SimpleBaseVo;

public class InsertDAO extends SimpleBaseDao {
    public SimpleBaseVo findByPrimaryKey(Object obj, Connection conn) throws FindRecordException {
        return null;
    }

    public ChildList selectByParent(SimpleBaseVo parent, Connection conn) throws FindRecordException {
        return null;
    }

    public void insert(SimpleBaseVo bizModel, Connection conn) throws CreateRecordException {
    }

    public void update(SimpleBaseVo bizModel, Connection conn) throws ModifyRecordException {
    }

    public void remove(SimpleBaseVo bizModel, Connection conn) throws DeleteRecordException {
    }

    public void insertLoginLog(String companyCode, String userCode, Connection conn) {

        PreparedStatement pStmt = null;
        ResultSet rs = null;
        try {
            pStmt = conn.prepareStatement(sqlInsert());
            setValuesForInsert(pStmt, companyCode, userCode);
            int count = pStmt.executeUpdate();
            conn.commit();
            
            if (count != 1)
                throw new SQLException("Unable to insert Login history log");
        } catch (SQLException sqe) {
            System.err.println("Error in InsertDAO.insert(): " + sqe.getMessage());
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException sqe) {
                System.err.println("Error in InsertDAO.insert() closing rs:" + sqe.getMessage());
            }

            try {
                if (pStmt != null)
                    pStmt.close();
            } catch (SQLException sqe) {
                System.err.println("Error in InsertDAO.insert() closing stmt:" + sqe.getMessage());
            }
        }

    }

    public String sqlInsert() {
        return " INSERT INTO T_LOGIN_HIST (COMPANY_CODE, USER_CODE, LOGIN_TIME, CREATE_USER, CREATE_DATE )"
                + "VALUES (?, ?, sysdate, ?, sysdate)";
    }

    protected void setValuesForInsert(PreparedStatement pStmt, String companyCode, String userCode) throws SQLException {
        int i = 1;
        pStmt.setString(i++, companyCode);
        pStmt.setString(i++, userCode);
        setNullableString(pStmt, i++, userCode);
    }
}
